import java.util.Arrays;

public class Solution279 {
    public int numSquares(int n) {
        int t = (int) Math.sqrt(n);
        int[] w = new int[t];
        for (int i = 1; i <= t; i++) {
            w[i - 1] = i * i;
        }
        int[] dp = new int[n + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int i = 0; i < t; i++) {
            for (int j = w[i]; j <= n; j++) {
                dp[j] = Math.min(dp[j], dp[j - w[i]] + 1);
            }
        }
        return dp[n];
    }
}
